package com.yiboshi.rehrs.config;

/**
 * @author hewenfeng 2021/3/29
 */

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yiboshi.rehrs.util.AperStringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Description 控制台输出 Swagger 接口文档地址
 * @Author Gao Hang Hang
 * @Date 2019-12-11 01:09
 **/
@Component
@Slf4j
@Data
public class ServerApplicationListener implements ApplicationListener<WebServerInitializedEvent> {

    @Value("${spring.profiles.active:}")
    String profile;
    @Value("${spring.application.name:}")
    String applicationName;

    private int port;

    private String ip;

    public String getServer() {
        return ip + ":" + port;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        try {
            RehrsSystemConfig.setProfile(profile);
            RehrsSystemConfig.setApplicationName(applicationName);
            InetAddress inetAddress = Inet4Address.getLocalHost();
            this.port = event.getWebServer().getPort();
            this.ip = inetAddress.getHostAddress();
            String swaggerKey = IdWorker.getId()+""+ AperStringUtils.randomNum(10);
            swaggerKey = RehrsSystemConfig.getSwaggerKey();
            log.info("项目启动启动成功！接口文档地址: http://" + getServer() + "/docs.html?key="+swaggerKey);
            if (profile.equals("dev")) {
                log.info("项目启动启动成功！接口文档地址: http://localhost:" + getPort() + "/docs.html?key="+swaggerKey);
            }
            RehrsSystemConfig.setServerIp(this.ip);
            RehrsSystemConfig.setServerPort(this.port);
            RehrsSystemConfig.setSwaggerKey(swaggerKey);
            return;
        } catch (UnknownHostException e) {
            log.error("", e);
        }
        RehrsSystemConfig.setProfile(profile);
        RehrsSystemConfig.setServerIp("local");
        RehrsSystemConfig.setServerPort(this.port);
    }

}

